<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form name="search-option__box" :inline="true">
      <el-form-item>
        <el-button type="primary" @click="addDept">新增部门</el-button>
        <el-button icon="el-icon-refresh" @click="fetchData" />
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      row-key="id"
      :data="deptList"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :header-cell-style="{ background: '#fafafa' }"
      default-expand-all
      border
    >
      <el-table-column prop="name" label="部门名称" />
      <el-table-column prop="dept_key" label="部门编号" />
      <el-table-column prop="order" label="排序" width="100" align="center" />
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="editDept(scope.row)">编辑</el-button>
          <el-button type="text" @click="singleDeleteDept(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer :title="deptDrawerTitle" :visible.sync="deptDrawerShow" direction="rtl" :before-close="handleCloseDrawer">
      <div class="drawer-container-scroll">
        <el-form ref="deptForm" :model="deptForm" :rules="deptFormRules" label-width="90px">
          <el-form-item label="上级部门">
            <div class="select-container">
              <SelectTree
                ref="treeSelect"
                v-model="deptForm.parent_id"
                :data="deptOptions"
              />
            </div>
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="deptForm.name" placeholder="请输入部门名称" />
          </el-form-item>
          <el-form-item label="部门编号">
            <el-input v-model="deptForm.dept_key" placeholder="请输部门编号" />
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input-number v-model="deptForm.order" :min="1" :max="999" label="排序序号" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="deptForm.disabled">
              <el-radio :label="false">启用</el-radio>
              <el-radio :label="true">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="deptForm.desc" type="textarea" :rows="2" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="drawer-footer__btn">
          <el-button @click="handleCloseDrawer">取 消</el-button>
          <el-button type="primary" @click="saveSubmit">保 存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import apiDept from '@/api/system/dept'
import SelectTree from '@/components/SelectTree'

const defaultForm = {
  name: '',
  parent_id: null,
  dept_key: '',
  order: 1,
  disabled: false,
  owner: '',
  phone: '',
  email: '',
  desc: ''
}
export default {
  components: { SelectTree },
  data() {
    return {
      deptList: [],
      deptOptions: [],
      listLoading: false,
      deptDrawerShow: false,
      deptDrawerTitle: '新增部门',
      submitType: 0, // 0:新增 1:编辑
      deptForm: defaultForm,
      deptFormRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        dept_key: [
          { required: true, message: '部门编号不能为空', trigger: 'blur' }
        ],
        order: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      apiDept.getDeptList().then(response => {
        this.deptList = response.data
        this.total = response.count
      })
      this.listLoading = false
    },
    // 获取部门、角色选项列表
    getDeptOptions() {
      apiDept.getDeptOptions().then(response => {
        this.deptOptions = response.data
      })
    },
    handleCloseDrawer() {
      this.deptDrawerShow = false
    },
    addDept() {
      this.getDeptOptions()
      this.deptDrawerShow = true
      this.deptDrawerTitle = '新增部门'
      this.submitType = 0
      this.deptForm = Object.assign({}, defaultForm)
    },
    editDept(row) {
      this.getDeptOptions()
      this.deptDrawerShow = true
      this.deptDrawerTitle = '编辑部门'
      this.submitType = 1
      this.deptForm = Object.assign({}, row)
    },
    async saveSubmit() {
      await this.$refs.deptForm.validate(async validate => {
        if (validate) {
          if (this.submitType === 0) {
            await apiDept.createDept(this.deptForm).then(response => {
              this.$message.success(response.message || '新增成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          } else {
            await apiDept.updateDept(this.deptForm).then(response => {
              this.$message.success(response.message || '编辑成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          }
          this.deptDrawerShow = false
          await this.fetchData()
        }
      })
    },
    async singleDeleteDept(row) {
      const data = [row.id]
      await this.deleteSubmit(data)
    },
    async deleteSubmit(data) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        await apiDept.deleteDept(data).then(async response => {
          this.$message.success(response.message || '删除成功')
          await this.fetchData()
        })
      })
    }
  }
}
</script>
